package com.peng.leetcode.search.binarysearch;

/**
 * SearchRange
 * 34. 在排序数组中查找元素的第一个和最后一个位置
 * https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
 *
 * @author: lupeng6
 * @create: 2023/3/9 20:18
 */
public class SearchRange {

    public int[] searchRange(int[] nums, int target) {
        if (nums == null || nums.length == 0) {
            return new int[]{-1, -1};
        }
        int i1 = searchLower(nums, target);
        if (i1 == -1 || nums[i1] != target) {
            return new int[]{-1, -1};
        }
        int i2 = searchHigh(nums, target);
        return new int[]{i1, i2};
    }

    private int searchLower(int[] nums, int target) {
        int l = 0;
        int r = nums.length - 1;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            if (nums[mid] < target) {
                l = mid + 1;
            } else if (nums[mid] > target) {
                r = mid - 1;
            } else {
                if (mid == 0 || nums[mid - 1] != target) {
                    return mid;
                } else {
                    r = mid - 1;
                }
            }
        }
        return -1;
    }


    private int searchHigh(int[] nums, int target) {
        int l = 0;
        int r = nums.length - 1;
        while (l <= r) {
            int mid = l + (r - l) / 2;
            if (nums[mid] < target) {
                l = mid + 1;
            } else if (nums[mid] > target) {
                r = mid - 1;
            } else {
                if (mid == nums.length - 1 || nums[mid + 1] != target) {
                    return mid;
                } else {
                    l = mid + 1;
                }
            }
        }
        return -1;
    }
}
